// 创建实例
var  pbbTable = new PbbTable();
//部门
var pbbPkDept="1002O110000000000MJ3";
//表索引
var pbbJyIndex,pbbZgIndex;

function PbbTable() {
    this.setCurrentDate=function (date) {
        var month=Number(date.getMonth())+ 1
        var year = date.getFullYear();
        this.month=month;
        this.year=year;
        this.currentDate= year+"年"+month+"月"
    }
    this.year="";
    this.month="";
    this.currentDate="";
    //数据
    this.jyData=[];
    this.zgData=[];
    this.getData=function () {
        //从员工表中获取--条件：部门、
        var result = commonAjax("post","/jx/pbb/getTableDataByEmp",{"pkDept":pbbPkDept});
        this.jyData=result.jyData;
        this.zgData=result.zgData
        return result
    }
    this.getData2=function () {
        //从员工表中获取--条件：部门、
        var result = commonAjax("post","/jx/pbb/getTableDataByJxAssessPbb",{"year":this.year,"month":this.month});
        this.jyData=result.jyData;
        this.zgData=result.zgData
        return result
    }
    //初始化两表
    this.init=function (){
        this.initYuanGong();
        this.initZhuGuan();
    }
    //初始化检验员表
    this.initYuanGong=function () {
        $("#pbbIndex_yuangong_table").edatagrid({
            columns:this.getColumns("检验员"),
            toolbar:"#pbbTableToolbarA",
            data:this.jyData,
            showFooter:true,
            bodyCls:'opal-txt_bold',
            autoSave:true,
            onBeforeEdit:function (index, row) {
                //编辑索引
                pbbJyIndex=index;
            },
            onBeginEdit:function (index, row) {
                //赋默认值
                pbbEditObject("assessDept").combobox("setValue","OQC");
            },
            onAfterEdit:function (index, row, changes) { //完成一行
                //页脚行
                pbbJyFooter(index,row);
                //主管数据刷新
                pbbZhuGuanRefresh()
            }
        })

    }
    //初始化主管表
    this.initZhuGuan=function () {
        $("#pbbIndex_zhuguan_table").edatagrid({
            toolbar:"#pbbTableToolbarB",
            columns:this.getColumns("主管"),
            data:this.zgData,
            showFooter:true,
            bodyCls:'opal-txt_bold',
            autoSave:true,
            onBeforeEdit:function (index, row) {
                pbbZgIndex=index;
            },
            onBeginEdit:function (index, row) {
                //赋默认值
               pbbEditObject("assessDept").combobox("setValue","OQC");
            },
            onAfterEdit:function (index, row, changes) { //完成一行
                pbbZgFooter()
            }
        })
    }

    this.height=function (elnameId) {
        var obj=  document.getElementById(elnameId)
        return obj.clientHeight;
    }

    this.getColumns=function (empType) {
        var dept="<span style='font-size: 18px;letter-spacing:5px'>品保部绩效考核统计表（"+empType+"）</span>"
        //字段
        var column=[ [{"field": 'id3', "title": dept,"align": "center", "colspan":10}],
            [{"title": '考核部门（科室）',"align": "center", "colspan":3},
                {"title": 'PQC、OQC、IQC、中控室', "align": "center","colspan":3},
                {"title": '考核周期',"align": "center","colspan":3},
                {"field": 'id2', "title": this.currentDate, "align": "center","colspan":1}]];
        var column1=[
                {"field": 'empName', "title": '姓名', "width": '5%', "align": "center","editor": {"type": "text"}},
                {"field": 'empCode', "title": '工号', "width": '5%', "align": "center","editor": {"type": "text"}},
                {"field": 'postName', "title": '岗位名称', "width": '5%', "align": "center","editor": {"type": "text"}},
                {"field": 'assessDept', "title": '考核部门', "width": '5%', "align": "center","editor": {"type": "combobox","options": {editable:false,valueField:"v",textField:"t",
                            panelHeight:'auto',data:[{v:'中控室',t:'中控室'},{v:'IQC',t:'IQC'},{v:'OQC',t:'OQC'},{v:'PQC',t:'PQC'}],"onChange":assessDeptOnChange
                }}},
            // {"field": 'efficientGroup', "title":'高效班组', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
            // {"field": 'personEfficiency', "title": '个人检验效<br/>率', "width": '5%',"align": "center","editor": {"type":"textbox", "options": {}}},
                {"field": 'score5S',"title": '5S得分',"width": '5%',"align": "center",
                        "editor": {"type": "textbox", "options": {}}},
                {"field": 'performanceBonusNorm', "title": '综合绩效奖<br/>标准', "width": '5%',"align": "center","editor": {"type":"textbox", "options": {"onChange":pbbResultMoneyTotal}}},
                {"field": 'attendanceRate', "title": '出勤率', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {"onChange":pbbResultMoneyTotal}}},
                {"field": 'otherAssess', "title": '其他考核F1', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {"onChange":pbbResultMoneyTotal}}},
                {"field": 'resultMoney', "title": '综合<br/>绩效（元）', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
                {"field": 'remarks', "title": '备注',"width": '55%', "align": "center","editor": {"type":"textarea"}}
            ]

        if (empType=="检验员"){
            var  zhuGuanName={"field": "empZhuguan", "title": "所属主管", "width": "5%", "align": "center","editor": {"type": "text"}}
            column1.splice(3,0,zhuGuanName);
            var  testWeight= {"field": 'testWeight',"title": '个人检验效<br/>率',"width": '5%',"align": "center",
                "editor": {"type": "textbox", "options": {"onChange":pbbPerformanceBonusNormTotal}}};
            var  entiretyPlanA=  {"field": 'entiretyPlanA',"title": '配制车间<br/>生产效率（A）',"width": '5%',"align": "center",
                "editor": {"type": "textbox", "options": {"onChange":pbbPerformanceBonusNormTotal}}}
            var  entiretyPlanB= {"field": 'entiretyPlanB',"title": '包装车间<br/>生产效率（B）',"width": '5%',"align": "center",
                "editor": {"type": "textbox", "options": {"onChange":pbbPerformanceBonusNormTotal}}}
            var  checkPrecision= {"field": 'checkPrecision', "title": '检验准确率<br/>(W)', "width": '5%',"align": "center","editor": {"type": "textbox", "options":  {"onChange":pbbPerformanceBonusNormTotal}}}
            var  exceptionReport= {"field": 'exceptionReport', "title": '成品异常报<br/>告跟进及时<br/>率(K)', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {"onChange":pbbPerformanceBonusNormTotal}}}
            column1.splice(5,0,testWeight,entiretyPlanA,entiretyPlanB,checkPrecision,exceptionReport);
            column[0][0].colspan=16
            column[1][1].colspan=9
            //主管少了一个字段让最后一个字段的宽度变成35%
            column1[column1.length-1].width="25%"
        }
        column.push(column1)
        return column;
    }

    function assessDeptOnChange(newValue,oldValue){
        var entiretyPlanA = pbbEditObject("entiretyPlanA");
        if (entiretyPlanA){
            var entiretyPlanB = pbbEditObject("entiretyPlanB");
            var exceptionReport = pbbEditObject("exceptionReport");
            switch (newValue) {
                case '中控室':
                    //配制车间生产效率（A）、检验权重（Q）、检验准确率（W）
                    //禁用    exceptionReport(成品异常报<br/>告跟进及时<br/>率(K))
                    entiretyPlanB.textbox("disable")
                    entiretyPlanB.textbox("setValue","")
                    exceptionReport.textbox("disable")
                    entiretyPlanA.textbox("enable")
                    break;
                case 'PQC':
                case 'OQC':
                    entiretyPlanA.textbox("disable")
                    entiretyPlanA.textbox("setValue","")
                    entiretyPlanB.textbox("enable")
                    exceptionReport.textbox("enable")
                    break;
                case 'IQC':
                    //检验准确率（W）  entiretyPlanB(包装车间)（B） 、检验权重（Q）
                    entiretyPlanA.textbox("disable")
                    entiretyPlanA.textbox("setValue","")
                    exceptionReport.textbox("disable")
                    exceptionReport.textbox("setValue","")
                    entiretyPlanB.textbox("enable")
                    break;

            }
        }

    }

    //计算绩效奖金标准方法
    function pbbPerformanceBonusNormTotal(){
        var assessDept=pbbEditObject("assessDept").combobox("getValue");
        var performanceBonusNorm = pbbEditObject("performanceBonusNorm")                  //绩效标准
        var B = Number(pbbEditObject("entiretyPlanB").textbox("getValue"));     //entiretyPlanB(包装车间)
        var K = Number(pbbEditObject("exceptionReport").textbox("getValue")); //成品异常报告跟进及时率(K)
        var A = Number(pbbEditObject("entiretyPlanA").textbox("getValue"));     //配制车间生产效率（A）
        var Q = Number(pbbEditObject("testWeight").textbox("getValue"));           //检验权重(Q)
        var W = Number(pbbEditObject("checkPrecision").textbox("getValue"));   //检验准确率<br/>(W)
        var resultValue="0";
        switch (assessDept) {
            case '中控室':
               //且A≥95%, Q≥88%                    0
                //99.8%≤W＜99.9%且A≥95%,  88%＜Q≤92%     400
               // 99.9%≤W＜100% 且A≥95%, 92%＜Q≤95%      500
               // W=100%且A≥95%, Q≥95%                     600

                if((99.8<=W) && (A>=95 &&(88 <= Q && Q<92))){
                    resultValue="400";
                }

                if ((99.9<=W) && (A>=95 && (92<Q && Q<=95))){
                    resultValue="500";
                }
                if (W==100 && (A>=95 && Q>=95)){
                    resultValue="600";
                }
                break;
            case 'PQC':
                //99.5%≤W＜99.75%  且B≥98%, 88%＜Q≤92%，K≥90%     400
                if((99.5<=W) && (B >=98 && 88 <= Q  && K>=90)){
                    resultValue="400";
                }

                //99.75%≤W＜100%  且B≥98%,92%＜Q≤95%，K≥90%       500
                if ((99.75<=W ) && (B >=98 && 92 <= Q && K>=90)){
                    resultValue="500";
                }
                //W=100% 且B≥98%, Q≥95%，K≥90%                    600
                if (W==100 && (B>=98 && Q >= 95 && K>=90)){
                    resultValue="600";
                }

                break;
            case 'OQC':
                //99.8%≤W＜99.9%且B≥98%，88%＜Q≤92%，K≥90%    400
                //99.9%≤W＜100%且B≥98%, 92%＜Q≤95%，K≥90%     500
                //W=100%且B≥98%, Q≥95%，K≥90%                 600
                if((99.8<=W) && (B >=98 && 88 <= Q  && K>=90)){
                    resultValue="400";
                }

                if ((99.9<=W) && (B >=98 && 92<=Q  && K>=90)){
                    resultValue="500";
                }

                if (W==100 &&(B>=98 && Q>=95 && K>=90)){
                    resultValue="600";
                }
                break;
            case 'IQC':
                //99.5%≤W＜99.9%且B≥98%,88%＜Q≤92%     400    q
                //99.9%≤W＜100%且B≥98%, 92%＜Q≤95%     500
                //W=100%且B≥98%, Q≥95%                600
                if(99.5<=W && (B >=98 && 88 <= Q)){
                    resultValue="400";
                }

                if (99.9<=W && (B >=98 && 92<= Q )){
                    resultValue="500";
                }

                if (W==100 && (B >=98 && 95 <= Q)){
                    resultValue="600";
                }
                break;

        }
        performanceBonusNorm.textbox("setValue",resultValue);
    }

    //计算最终绩效奖金标准
    function pbbResultMoneyTotal() {
        var resultMoney = pbbEditObject("resultMoney")                  //绩效标准
        var bonusNorm = pbbEditObject("performanceBonusNorm").textbox("getValue")  //绩效标准
        bonusNorm=bonusNorm?Number(bonusNorm):0;
        var rate = pbbEditObject("attendanceRate").textbox("getValue")  //出勤率
        rate=rate?Number(rate)/100:0;
        var other = pbbEditObject("otherAssess").textbox("getValue")  //其它考核
        other=other?Number(other):0;
        var money = fomatFloat(bonusNorm*rate-other,2);
        resultMoney.textbox("setValue",money);
    }
    //完成编辑一行触发：刷新页脚行
    function pbbJyFooter(){
        //获取检验员表中所有行
        var rows = $('#pbbIndex_yuangong_table').datagrid('getRows');
        //获取页尾行
        var footers= $('#pbbIndex_yuangong_table').datagrid('getFooterRows');
        let resultTotal=0;
       //每组
        for (let footer of footers){
           let array=[];  //定义数组，保存每个所属主管的最终绩效奖金标准数据
           let name=footer.empCode  //获取主管姓名
           //算每组的合计
           for (let row of rows){
               var empZhuguan= row.empZhuguan; //获取所属主管姓名
               if(name==empZhuguan){
                   var resultMoney = row.resultMoney;
                   //若是Undefined证明这行还没有操作，变为0
                   array.push(resultMoney?resultMoney:0)
               }
           }
           //求和
           if (array.length>0){   //reduce不允许是空数组
               var sum= array.reduce((r,v)=>{
                   r=r?r:0;v=v?v:0;
                   return  Number(r)+Number(v)
               });
               sum=fomatFloat(sum,2);
               footer.resultMoney=sum
               resultTotal+=sum;
           }

        }
       //合计
        for (let footer of footers){
            if (footer.empCode=="合计"){
                footer.resultMoney=fomatFloat(resultTotal,2)
            }
        }

        $('#pbbIndex_yuangong_table').datagrid("reloadFooter",footers)
    }

    function pbbZgFooter() {
        //获取检验员表中所有行
        var rows = $("#pbbIndex_zhuguan_table").datagrid('getRows');
        //获取页尾行
        var footers= $('#pbbIndex_zhuguan_table').datagrid('getFooterRows');
        //合计
        var totalMoney=0;
        for (let row of rows){
           var rm=Number(row.resultMoney)
            rm=rm?rm:0;
            totalMoney+=rm;
        }
        footers[0].resultMoney=fomatFloat(totalMoney,2);
        $('#pbbIndex_zhuguan_table').datagrid("reloadFooter",footers);
    }

    //检验员绩效表每完成一行刷新主管表的数据：完成绩效标准的赋值
    function pbbZhuGuanRefresh() {
        //获取主管原数据
        //{toal:0,footer:[{empCode: "合计", resultMoney: "0"}],rows:[{id: null, empCode: "0030514", empName: "陈卓明", empKezhang: null, empZhuguan: null, …}]}
        var zgData = pbbTable.zgData;
        //获取检验员表中所有行
        var rows = $('#pbbIndex_yuangong_table').datagrid('getRows');
        //获取主管表的每行数据
        var datas = zgData.rows;
        //循环主管表每行数据
        for (let data of datas){

            let array=[];  //定义数组，保存每个所属主管的最终绩效奖金标准数据
            var name=data.empName  //获取主管姓名
            for (let row of rows){
                var empZhuguan= row.empZhuguan; //获取所属主管姓名

                if(name==empZhuguan){
                    var resultMoney = row.resultMoney;
                    //若是Undefined证明这行还没有操作，变为0
                    array.push(resultMoney?resultMoney:0)
                    //部门
                    data.assessDept=row.assessDept
                }

            }

            //求和
            if (array.length>0) {
                var sum = array.reduce((r, v) => {
                    r = r ? r : 0;
                    v = v ? v : 0;
                    return Number(r) + Number(v)
                });
                //主管公式：每组平均值*1.4但是不能大于800
                let bonusNorm = (sum / array.length) * 1.4;
                //往原主管数据添加属性performanceBonusNorm并赋值
                data.performanceBonusNorm = fomatFloat(bonusNorm > 800 ? 800 : bonusNorm, 2);
            }else {
                data.performanceBonusNorm = 0;
            }
        }
        //刷新主管表的数据
        $("#pbbIndex_zhuguan_table").datagrid("loadData",zgData)

    }
}

//刚进页面初始化
(function () {
    //表格初始化
    pbbTable.setCurrentDate(new Date());
    pbbTable.getData();
    pbbTable.init();
    //按钮高度初始化
    var pbbIndexButton = document.getElementById("pbbIndex_button");
    var pbbIndexButtonHeight = pbbIndexButton.offsetHeight;
    pbbIndexButton.style.lineHeight=pbbIndexButtonHeight+"px";
})()

//获取表中的编辑器jquery_easyui对象
function pbbEditObject(fieldName) {
    var obj;
    try{
        obj= $("#pbbIndex_yuangong_table").datagrid('getEditor',{index:pbbJyIndex,field:fieldName}).target;
    }catch (e) {
        obj= $("#pbbIndex_zhuguan_table").datagrid('getEditor',{index:pbbZgIndex,field:fieldName})
           if (obj){
               obj= obj.target;
           }
    }
  return obj
}




